/**
 * 
 */
package x.java.tea;

import java.io.IOException;



/**
 * @author qiangli
 *
 */
public class TreeNodeInjector extends IteratorInjector {
	protected TreeNode treeNode;
	
	private int progress;
	
	/**
	 * 
	 */
	public TreeNodeInjector(TreeNode treeNode) {
		this.it = treeNode.children();
		this.treeNode = treeNode;
		this.progress = 0;
	}

	@Override
	protected void setBuf(Object obj) {
		TreeNode n = (TreeNode) obj;
		if (n.isLeaf()) {
			setBuf(n);
		} else {
			Injector inj = new TreeNodeInjector(n);
			setBuf(inj);
		}	
	}
	
	protected void setBuf(TreeNode n) {
		setBuf("<"+n.getObject()+"/>\r\n");
	}
	
	@Override
	public int inject(byte[] b) throws IOException {
		int c = doInject(b);
		if (c != -1) {
			return c;
		}
		//
		if(progress == 0) {
			progress++;
			preInject();
			c = doInject(b);
			if (c != -1) {
				return c;
			}
		} 
		//
		if(progress == 1){
			c = super.inject(b);
			if (c != -1) {
				return c;
			}
			progress++;
		}
		//
		if (progress == 2) {
			progress++;
			postInject();	
			c = doInject(b);
			if (c != -1) {
				return c;
			}
		}
		return -1;
	}

	protected void preInject() throws IOException {
		setBuf("<"+treeNode.getObject()+">\r\n");
	}
	
	protected void postInject() throws IOException {
		setBuf("</"+treeNode.getObject()+">\r\n");
	}
}
